<template>
	<view :class="vuex_theme">
		<u-navbar class="video-detail-content-title" title="视频" :is-back="false" :title-bold="true"
			:background="{background: vuex_bar_color}" :border-bottom="false">
			<view class="slot-wrap" slot="right">
				<u-circle-progress v-if="videoUploadItem.progress" :width="40" border-width="3"
					class="pre-box-item-progress slot-wrap-right" :percent="videoUploadItem.progress" bg-color="none"
					:round="true" :active-color="progressColor(videoUploadItem.progress)">
				</u-circle-progress>
				<u-icon v-else class="slot-wrap-right" name="plus" @click="chooseVideo" size="40"></u-icon>
			</view>
		</u-navbar>
		<u-waterfall v-model="flowList" ref="uWaterfall">
			<template v-slot:left="{ leftList }">
				<view class="video-warter color-gradual" v-for="(item, index) in leftList" :key="index"
					@click="showDetal(item)" @longpress="oprate(item)">
					<u-lazy-load :threshold="-10" border-radius="10" class="color-gradual-same"
						:image="$u.http.config.baseUrl + encodeURI(item.url) + '?x-oss-process=video/snapshot,t_5000,m_jpg'"
						:index="index"></u-lazy-load>
					<view class="video-title">{{ item.name }}</view>
				</view>
			</template>
			<template v-slot:right="{ rightList }">
				<view class="video-warter color-gradual" v-for="(item, index) in rightList" :key="index"
					@click="showDetal(item)" @longpress="oprate(item)">
					<u-lazy-load :threshold="-10" border-radius="10" class="color-gradual-same"
						:image="$u.http.config.baseUrl + encodeURI(item.url) + '?x-oss-process=video/snapshot,t_5000,m_jpg'"
						:index="index"></u-lazy-load>
					<view class="video-title">{{ item.name }}</view>
				</view>
			</template>
		</u-waterfall>
		<u-loadmore :status="loadStatus" @loadmore="addRandomData"></u-loadmore>
		<u-back-top class="color-gradual" :scroll-top="scrollTop" top="1"></u-back-top>
		<u-action-sheet class="color-ico-gradual" :list="operationList" @click="operationClick" v-model="operationShow" :cancel-btn="false">
		</u-action-sheet>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';  
	export default {
		computed: {  
			...mapState(['vuex_bar_color'])  
		}, 
		data() {
			return {
				loadStatus: 'loadmore',
				flowList: [],
				videoUploadItem: {
					progress: 0
				},
				operationItem: {},
				operationShow: false,
				operationList: [{
					text: '删除',
					color: 'red',
					fontSize: 28
				}],
				scrollTop: 0,
				total: 10,
				
			};
		},
		onLoad() {
			this.addRandomData();
		},
		onShow() {
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onReachBottom() {
			if (this.flowList.length < this.total) {
				this.addRandomData();
			}
		},
		methods: {
			addRandomData() {
				if (this.flowList.length >= this.total) {
					this.loadStatus = 'nomore'
					return
				}
				this.loadStatus = 'loading'
				this.$u.get('/api/file/video/list?offset=' + this.flowList.length).then(res => {
					const {
						total,
						data
					} = res
					this.total = total
					data.forEach(item => {
						item.id = this.$u.guid();
						this.flowList.push(item);
					})
					if (this.flowList.length >= this.total) {
						this.loadStatus = 'nomore'
					} else {
						this.loadStatus = 'loadmore'
					}
				}).catch(e => {
					this.loadStatus = 'loadmore'
				})
			},
			showDetal(item) {
				this.$u.route({
					url: 'pages/cloud/video/detail',
					params: {
						videoName: item.name
					}
				})
			},
			oprate(item) {
				this.operationItem = item
				this.operationShow = true
			},
			operationClick(index) {
				if (index === 0) {
					this.delete(this.operationItem)
				}
			},
			chooseVideo() {
				uni.chooseVideo({
					success: res => {
						const file = res.tempFile
						this.uploadVideo(file)
					}
				})
			},
			progressColor(progress) {
				const r = 230 - progress * 2;
				const g = 150 + parseInt(progress / 2);
				const b = 10 + parseInt(progress);
				return 'rgb(' + r + ', ' + g + ', ' + b + ')'
			},
			uploadVideo(file) {
				const self = this;
				self.videoUploadItem.progress = 10
				const fileSize = file.size;
				const chunkSize = 5 * 1024 * 1024,
					partCount = Math.ceil(fileSize / chunkSize);
				let progressNum = 0,
					successAllCount = 0;
				const mergingFile = () => {
					self.videoUploadItem.progress = 99
					self.$u.post('/api/file/video/mergingPart', {
						fileName: file.name
					}).then(res => {
						res.id = self.$u.guid()
						self.flowList.unshift(res)
						self.videoUploadItem.progress = 0
						self.$refs.uTips.show({
							title: '上传成功',
							type: 'error',
							duration: '2300'
						})
					}).catch(e => {
						console.error(e)
						self.$refs.uTips.show({
							title: '上传失败',
							type: 'error',
							duration: '2300'
						})
					})
				}
				const getChunkInfo = (file, currentChunk, chunkSize) => {
					const start = currentChunk * chunkSize
					const end = Math.min(fileSize, start + chunkSize)
					const chunk = file.slice(start, end)
					return {
						start,
						end,
						chunk
					}
				}
				const uploadPart = (index) => {
					const {
						chunk
					} = getChunkInfo(file, index, chunkSize)
					const chunkFR = new FileReader()
					chunkFR.readAsDataURL(chunk)
					chunkFR.addEventListener('load', blob => {
						let blobBase64 = blob.target.result;
						blobBase64 = blobBase64.substring(37);
						uni.request({
							url: self.$u.http.config.baseUrl + '/api/file/video/uploadBlobPart',
							method: 'POST',
							data: {
								fileName: file.name,
								fileSize: fileSize,
								partCount: partCount,
								index: index,
								blobBase64: blobBase64
							},
							success: function() {
								successAllCount++;
								progressNum = Math.ceil(successAllCount / partCount * 98)
								self.videoUploadItem.progress = progressNum
								if (successAllCount >= partCount) {
									mergingFile();
								} else {
									uploadPart(index+ 1)
								}
							},
							fail: function(e) {
								console.error(e)
								self.videoUploadItem.progress = 0
								self.$refs.uTips.show({
									title: '上传失败',
									type: 'error',
									duration: '2300'
								})
							}
						})
					}, false)
				}
				uploadPart(0)
			},
			delete(item) {
				const self = this
				this.$u.delete('/api/file/video/delete/' + item.name).then(res => {
					const length = this.flowList.length
					for (let i = 0; i < length; i++) {
						const e = this.flowList[i]
						if (e.id == item.id) {
							this.flowList.splice(i, 1)
							break
						}
					}
					if (this.imageSwipeCurrent > this.flowList.length - 3) {
						this.addRandomData()
					}
					this.$refs.uWaterfall.remove(item.id)
					this.total--
				})
			}
		}
	};
</script>


<style lang="scss" scoped>
	.video-warter {
		border-radius: 8px;
		margin: 5px;
		padding: 8px;
		position: relative;
	}

	.slot-wrap-right {
		margin: 2rpx 20rpx;
	}

	.u-close {
		position: absolute;
		top: 32rpx;
		right: 32rpx;
	}

	.video-img-wrap {}

	.video-image {
		width: 100%;
		border-radius: 4px;
	}

	.video-title {
		font-size: 20rpx;
		margin-top: 5px;
		color: $u-tips-color;
		word-break: break-all;
	}

	.video-dialog {
		width: 100%;
		height: 100%;
	}

	.upload-btn {
		position: absolute;
		right: 0;
		bottom: 0;
	}
</style>
